package com.tech.utils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

public class SimpleHttpURLUtils {

	@SuppressWarnings("unchecked")
	public static Map<String, Object> doPost(String requestUrl,
			Map<String, Object> reqParams) throws Exception {
		String content = doPost(requestUrl, reqParams, "GBK");
		Map<String, Object> httpResult = JsonUtils.strToObject(content,
				Map.class);
		return httpResult;
	}

	@SuppressWarnings("unchecked")
	public static Map<String, Object> doGet(String requestUrl,
			Map<String, Object> reqParams) throws Exception {
		String content = doGet(requestUrl, reqParams, "GBK");
		Map<String, Object> httpResult = JsonUtils.strToObject(content,
				Map.class);
		return httpResult;
	}

	public static String doPost(String requestUrl,
			Map<String, Object> reqParams, String encoding) throws Exception {
		return execute(requestUrl, reqParams, "POST", encoding);
	}

	public static String doGet(String requestUrl,
			Map<String, Object> reqParams, String encoding) throws Exception {
		return execute(requestUrl, reqParams, "GET", encoding);
	}

	private static String execute(String requestUrl,
			Map<String, Object> reqParams, String requestMethod, String encoding)
			throws Exception {
		HttpURLConnection conn = null;
		String con = JsonUtils.objToString(reqParams);
		URL url = new URL(requestUrl);
		conn = (HttpURLConnection) url.openConnection();
		conn.setRequestMethod(requestMethod);
		conn.setDoOutput(true);
		conn.setRequestProperty("User-Agent", "Micah rum");
		conn.setRequestProperty("Content-type", "application/json; charset="
				+ encoding);
		conn.setConnectTimeout(10000);
		conn.setReadTimeout(10000);
		conn.connect();
		conn.getOutputStream().write(con.getBytes(encoding));
		conn.getOutputStream().flush();
		conn.getOutputStream().close();
		BufferedReader br = new BufferedReader(new InputStreamReader(
				conn.getInputStream(), encoding));
		StringBuffer bs = new StringBuffer();
		String line;
		while ((line = br.readLine()) != null)
			bs.append(line + "\n");
		// LOG.error(
		// "\n[HttpURLUtils doPost] \nrequestUrl :{}\nreqParams :{}\nencoding :{}\nerrorMsg :{}",
		// new Object[] { requestUrl, reqParams, encoding,
		// e.toString() });
		br.close();
		conn.disconnect();
		return bs.toString();
	}

}
